//
//  XSQBbanner.m
//  kongge
//
//  Created by xiaoshunliang on 16/2/1.
//  Copyright © 2016年 nil. All rights reserved.
//

#import "XSQBanner.h"
#import "UIView+XPKit.h"

@interface XSQBanner()<UIScrollViewDelegate>
@property(strong,nonatomic) UIScrollView *direct;
//轮播图片名字的数组
@property(strong,nonatomic) NSArray *imageArr;
@property(strong,nonatomic) NSTimer *timer;
//点击图片出发Block
@property(copy,nonatomic) imageClickBlock clickBlock;
//是否启用定时器
@property(nonatomic,assign) BOOL isBeginTimer;

@end
@implementation XSQBanner
//获取ScrollView的X值偏移量
#define contentOffSet_x self.direct.contentOffset.x
//获取ScrollView的宽度
#define frame_width self.direct.frame.size.width
//获取ScrollView的contentSize宽度
#define contentSize_x self.direct.contentSize.width


-(instancetype)initWithFrame:(CGRect)frame
{
    if(self=[super initWithFrame:frame])
    {
        //初始化轮播ScrollView
        self.direct=[[UIScrollView alloc]init];
        self.direct.delegate=self;
        self.direct.pagingEnabled=YES;
        self.direct.frame=self.bounds;
        self.direct.contentOffset=CGPointMake(frame_width, 0);
        self.direct.showsHorizontalScrollIndicator=NO;
        [self addSubview:self.direct];
        
        //初始化轮播页码控件
        self.pageVC=[[UIPageControl alloc]init];
        //设置轮播页码的位置
        self.pageVC.frame=CGRectMake(0,self.frame.size.height-30, self.frame.size.width, 30);
        [self customPageVcWithSelectedImg:imgname(@"pagec1") NormalImg:imgname(@"pagec0")];
        [self addSubview:self.pageVC];
        
        self.time=5;
        
        self.isBeginTimer=YES;
    }
    return self;
}
#pragma mark-===========================定时器===============================
-(void)beginTimer
{
    self.isBeginTimer=YES;
    [self startTimer];
}

-(void)startTimer
{
    if(self.timer==nil && self.isBeginTimer)
    {
        self.timer =[NSTimer scheduledTimerWithTimeInterval:self.time target:self selector:@selector(timerSel) userInfo:nil repeats:YES];
    }
}

#pragma mark 不开启定时器
-(void)stopTimer
{
    [self destoryTimer];
    self.isBeginTimer=NO;
}

#pragma mark 摧毁定时器
-(void)destoryTimer
{
    [self.timer invalidate];
    self.timer=nil;
}

#pragma mark 定时器调用的方法
-(void)timerSel
{
    //获取并且计算当前页码
    CGPoint currentConOffSet=self.direct.contentOffset;
    currentConOffSet.x+=frame_width;
    
    //动画改变当前页码
    [UIView animateWithDuration:0.5 animations:^{
        self.direct.contentOffset=currentConOffSet;
    }completion:^(BOOL finished) {
        [self updataWhenFirstOrLast];
    }];
}

#pragma mark-========================UIScrollViewDelegate=====================
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self destoryTimer];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self startTimer];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //当最后或者最前一张图片时改变坐标
    [self updataWhenFirstOrLast];
}

#pragma mark-=====================轮播页码改变=====================
-(void)updataPageControl
{
    NSInteger index=(contentOffSet_x-frame_width)/frame_width;
    self.pageVC.currentPage=index;
}

#pragma mark -=====================其他一些方法===================
-(void)setTime:(CGFloat)time
{
    if(time>0)
    {
        _time=time;
        [self destoryTimer];
        [self startTimer];
    }
}

#pragma mark 重写图片名字的数组
-(void)setImageArr:(NSArray *)imageArr
{
    _imageArr=imageArr;
    
    [self addImageToScrollView];
    
    [self startTimer];
}

#pragma mark 图片点击事件
-(void)imageClick:(UITapGestureRecognizer *)tap
{
    UIView *view=tap.view;
    if(self.clickBlock)
    {
        self.clickBlock(view.tag);
    }
}

#pragma mark 根据图片名添加图片到ScrollView
-(void)addImageToScrollView
{
    /**
     *  清空掉之前的image
     */
    [self.direct removeAllSubviews];
    //创建一个可变数组
    NSMutableArray *imgMArr=[NSMutableArray arrayWithArray:self.imageArr];
    //添加第一个和最后一个对象到对应可变数组的最后一个位置和第一个位置
    if (imgMArr.count>0) {
        [imgMArr insertObject:[self.imageArr lastObject] atIndex:0];
        [imgMArr addObject:[self.imageArr firstObject]];
    }
    
    NSInteger tag=-1;
    for (NSString *name in imgMArr) {
        //将传进来的图片名在本地初始化
        UIImageView *imgView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:name]];
        
        //如果本地没有这张图片进行网络请求
        if(imgView.image ==nil)
        {
            imgView.contentMode=UIViewContentModeScaleAspectFill;
            imgView.clipsToBounds=YES;
            if ([name hasPrefix:@"http"]) {
                [imgView sd_setImageWithURL:[NSURL URLWithString:name] placeholderImage:defaultImg];
            }else{
                sdimg(imgView, name);
            }
        }
        //设置图片的坐标
        imgView.frame=CGRectMake(self.frame.size.width*(tag+1), 0, self.frame.size.width, self.frame.size.height);
        
        //设置tag
        imgView.tag=tag;
        tag++;
        
        //添加手势
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageClick:)];
        [imgView addGestureRecognizer:tap];
        //开启用户交互
        imgView.userInteractionEnabled=YES;
        [self.direct addSubview:imgView];
    }
    self.pageVC.numberOfPages=self.imageArr.count;
}

#pragma mark 判断是否第一或者最后一个图片,改变坐标
-(void)updataWhenFirstOrLast
{
    //当图片移动到最后一张时，动画结束移动到第二张图片的位置
    if(contentOffSet_x>=contentSize_x-frame_width)
    {
        self.direct.contentOffset=CGPointMake(frame_width, 0);
    }
    //当图片移动到第一张时，动画结束移动到倒数第二张的位置
    else if (contentOffSet_x<=0)
    {
        self.direct.contentOffset=CGPointMake(contentSize_x-2*frame_width, 0);
    }
    
    //更新PageControl
    [self updataPageControl];
}

#pragma mark 设置自定义分页样式
-(void)customPageVcWithSelectedImg:(UIImage *)selectedImg NormalImg:(UIImage *)normalImg
{
    [self.pageVC setValue:selectedImg forKey:@"_currentPageImage"];
    [self.pageVC setValue:normalImg forKey:@"_pageImage"];
    
}
//更新图片数组
- (void)updateImageArr:(NSArray *)imageNameArray AndImageClickBlock:(imageClickBlock)clickBlock{
    /**
     *  设置一张图片的时候不可以滚动
     */
    if (imageNameArray.count<=1) {
        [self stopTimer];
        self.direct.scrollEnabled = NO;
    }else{
        [self beginTimer];
         self.direct.scrollEnabled = YES;
    }
    
    self.direct.contentSize=CGSizeMake((imageNameArray.count+2)*frame_width,0);
    self.pageVC.numberOfPages=imageNameArray.count;
    
    if (_pageLocation == PageControlLocationLeft) {
         self.pageVC.frame =CGRectMake(10,self.frame.size.height-30,20 * _imageArr.count, 30);
    }else if (_pageLocation == PageControlLocationRight){
         self.pageVC.frame =CGRectMake(frame_width-  20 * imageNameArray.count,self.frame.size.height-30,20 * _imageArr.count, 30);
    }else{
         self.pageVC.frame=CGRectMake(0,self.frame.size.height-30, self.frame.size.width, 30);
    }

    //设置滚动图片数组
    self.imageArr=imageNameArray;
    //设置图片点击的Block
    self.clickBlock=clickBlock;

}

@end
